package com.example.prototype_2;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.net.nsd.NsdServiceInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class PrototypeActivity extends Activity implements OnClickListener, PictureCallback, ControlFragment.OnButtonClickedListener_Control, VoiceFragment.OnButtonClickedListener_Voice{

    Activity mAct = this;
    NsdHelper mNsdHelper = null;
    ChatConnection mConnection;
    Boolean RecognizerFlag;
    private Handler mUpdateHandler;
    private InetAddress mAddress;
    private int mPort = -1;
    private CameraSurfacePreview mCameraSurPreview = null;
    private String TAG = "Dennis";
    private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;


    /**
     * 三个Fragment
     */
    private ControlFragment controlFragment;
    private GestureFragment gestureFragment;
    private VoiceFragment voiceFragment;

    /**
     * 拍照按钮
     */
    private Button mCaptureButton = null;

    /**
     * 用于对Fragment进行管理
     */
    private FragmentManager fragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //初始化视频界面
        initCameraPreview();

        //初始化NSD
        initNSD();

        //初始化语音识别
        initVoice();

        // 初始化布局元素
        initViews();
        fragmentManager = getFragmentManager();

        // 第一次启动时选中第1个tab，即控制界面
        setTabSelection(1);
    }

    /**
     * 初始化视频界面
     */
    private void initCameraPreview(){

        //建立一个preview实例，并将它添加在layout的framework上
        FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
        mCameraSurPreview = new CameraSurfacePreview(this);
        preview.addView(mCameraSurPreview);
    }

    /**
     * 初始化NSD
     */
    private void initNSD(){
        mUpdateHandler = new Handler();
        mConnection = new ChatConnection(mUpdateHandler, mAct);
        mNsdHelper = new NsdHelper(this);
        mNsdHelper.initializeNsd();
    }

    /**
     * 初始化语音识别
     */

    private void initVoice(){

        //检查是否有语音识别程序
        PackageManager pm = getPackageManager();
        List activities = pm.queryIntentActivities(
                new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);

        if (activities.size() != 0) {
            RecognizerFlag = true;
        } else {
            RecognizerFlag = false;
        }
    }

    /**
     * 在这里获取到每个需要用到的控件的实例，并给它们设置好必要的点击事件。
     */
    private void initViews() {
        /**
         * 控制按钮、手势按钮、声控按钮、注册按钮、连接按钮、拍照按钮
         */
        Button controlButton = (Button) findViewById(R.id.button_control);
        Button gestureButton = (Button) findViewById(R.id.button_gesture);
        Button voiceButton = (Button) findViewById(R.id.button_voice);
        Button registerButton = (Button) findViewById(R.id.button_register);
        Button connectButton = (Button) findViewById(R.id.button_Connect);
        mCaptureButton = (Button) findViewById(R.id.button_capture);

        /**
         * 设置控制、手势、声控、注册、连接、拍照的监听
         */
        controlButton.setOnClickListener(this);
        gestureButton.setOnClickListener(this);
        voiceButton.setOnClickListener(this);
        registerButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (mConnection.getLocalPort() > -1) {
                    mNsdHelper.registerService(mConnection.getLocalPort());
                    showToast("注册成功" + mConnection.getLocalPort());
                } else {
                }

            }
        });
        connectButton.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                mNsdHelper.discoverServices();
                showToast("查找");
                NsdServiceInfo service = mNsdHelper.getChosenServiceInfo();
                if (service != null) {
                    mConnection.connectToServer(service.getHost(),
                            service.getPort());
                    showToast("连接" + service.getPort());
                } else {
                    showToast("未找到服务");
                }

            }});
        mCaptureButton.setOnClickListener(this);
    }



    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.button_gesture:
                // 当点击了手势按钮时，选中第1个tab
                setTabSelection(0);
                break;
            case R.id.button_control:
                // 当点击了控制按钮时，选中第2个tab
                setTabSelection(1);
                break;
            case R.id.button_voice:
                // 当点击了语音按钮时，选中第3个tab
                setTabSelection(2);
                break;

            case R.id.button_register:
                //当点击了注册按钮

                break;
            case R.id.button_capture:
                //当点击了拍照按钮
                mCaptureButton.setEnabled(false);

                // get an image from the camera
                mCameraSurPreview.takePicture(this);
            default:
                break;
        }
    }

    /**
     * 根据传入的index参数来设置选中的tab页。
     *
     * @param index
     *            每个tab页对应的下标。0表示消息，1表示联系人，2表示动态，3表示设置。
     */
    private void setTabSelection(int index) {
        // 每次选中之前先清楚掉上次的选中状态
        // 开启一个Fragment事务
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
        hideFragments(transaction);
        switch (index) {
            case 0:
                if (gestureFragment == null) {
                    // 如果GestureFragment为空，则创建一个并添加到界面上
                    gestureFragment = new GestureFragment();
                    transaction.add(R.id.content,gestureFragment);
                } else {
                    // 如果GestureFragment不为空，则直接将它显示出来
                    transaction.show(gestureFragment);
                }
                break;
            case 1:
                if (controlFragment == null) {
                    // 如果ControlFragment为空，则创建一个并添加到界面上
                    controlFragment = new ControlFragment();
                    transaction.add(R.id.content, controlFragment);
                } else {
                    // 如果ControlFragment不为空，则直接将它显示出来
                    transaction.show(controlFragment);
                }
                break;
            case 2:
                if (voiceFragment == null) {
                    // 如果VoiceFragment为空，则创建一个并添加到界面上
                    voiceFragment = new VoiceFragment();
                    transaction.add(R.id.content,voiceFragment);
                } else {
                    // 如果VoiceFragment不为空，则直接将它显示出来
                    transaction.show(voiceFragment);
                }
                break;
            case 3:
            default:
                break;
        }
        transaction.commit();
    }

    /**
     * 将所有的Fragment都置为隐藏状态。
     * 用于对Fragment执行操作的事务
     */
    private void hideFragments(FragmentTransaction transaction) {
        if (controlFragment != null) {
            transaction.hide(controlFragment);
        }
        if (gestureFragment != null) {
            transaction.hide(gestureFragment);
        }
        if (voiceFragment != null) {
            transaction.hide(voiceFragment);
        }
    }


    /**
     * 与Control界面的接口
     */
    public void onButtonClicked_control(String ButtonText){
        mConnection.sendMessage(ButtonText);
    }

    /**
     * 与Voice界面的接口
     */
    public void onButtonClicked_voice(){

        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
               RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
        startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);

        if (!RecognizerFlag) {
            Button speakButton = (Button) findViewById(R.id.button_recordStart);
            speakButton.setEnabled(false);
        }
    }

    /**
     * Handle the results from the recognition activity.
     */

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {

            // Fill the list view with the strings the recognizer thought it could have heard
            ArrayList<String> matches = data.getStringArrayListExtra(
                    RecognizerIntent.EXTRA_RESULTS);

            String stringA = "move forward";
            String stringB = "move back";
            String stringC = "turn left";
            String stringD = "turn right";
            String stringE = "no match";

            if (matches.get(0).equals(stringA)){
                mConnection.sendMessage(stringA);

            }
            else if (matches.get(0).equals(stringB)){
                mConnection.sendMessage(stringB);

            }
            else if (matches.get(0).equals(stringC)){
                mConnection.sendMessage(stringC);

            }
            else if (matches.get(0).equals(stringD)){
                mConnection.sendMessage(stringD);

            }
            else  {
                mConnection.sendMessage(stringE);
            }

        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {

        //save the picture to sdcard
        File pictureFile = getOutputMediaFile();
        if (pictureFile == null){
            Log.d(TAG, "Error creating media file, check storage permissions: ");
            return;
        }

        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);
            fos.close();

            Toast.makeText(this, "Image has been saved to " + pictureFile.getAbsolutePath(),
                    Toast.LENGTH_LONG).show();
        } catch (FileNotFoundException e) {
            Log.d(TAG, "File not found: " + e.getMessage());
        } catch (IOException e) {
            Log.d(TAG, "Error accessing file: " + e.getMessage());
        }

        // Restart the preview and re-enable the shutter button so that we can take another picture
        camera.startPreview();

        //See if need to enable or not
        mCaptureButton.setEnabled(true);
    }

    private File getOutputMediaFile(){
        //get the mobile Pictures directory
        File picDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

        //get the current time
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

        return new File(picDir.getPath() + File.separator + "IMAGE_"+ timeStamp + ".jpg");
    }

    public void showToast(final String text){
        mAct.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast toast = Toast.makeText(mAct, text, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();

            }
        });
    }

}
